package cubelabs.nexus.utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
//import org.junit.Test;


public class MailUtil {
	
	//@Test
	@SuppressWarnings("deprecation")
	public void testMail(){
		Map<String, Object> inputMap = new HashMap<String, Object>();

		//inputMap.put("to", toUser.getEmail());
		
		Map<String, Object> valueMap = new HashMap<String, Object>();
		String filename = new String();
		inputMap.put("subject", "Welcome to Meet Expert");
		
		valueMap.put("#USER_NAME#", "RAJU");
		filename = "WelcomeMessage.txt";
		
		//	inputMap.put("text", "Hi "+toUser.getName()+", Thanks for joining Meet Expert. Enhance your skills. -Meet Expert.");
		
		
		StringBuffer sb = new StringBuffer();
		try {
			DataInputStream dis = new DataInputStream(this.getClass().getClassLoader().getResourceAsStream(filename));
			String str = "";
			while (str != null) {
				str = dis.readLine();
				if (str != null) {
					sb.append(str);
					sb.append("\n");
				}
			}
		} catch (Exception ce) {
			ce.printStackTrace();
		}
		
		String emailMessage = sb.toString();
		
		Iterator<String> iterator = valueMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			String value = (String) valueMap.get(key);
			if (value == null) {
				continue;
			}
			if (value.contains("$")) {
				value = value.replaceAll("\\$", "\\\\\\$");
			}
			emailMessage = emailMessage.replaceAll(key, value);			
		}
		System.out.println("Email message :"+emailMessage);
	}

	public static void main(String[] args) {


/*		Map<String, Object> inputMap = new HashMap<String, Object>();
		StringBuffer sb = new StringBuffer();
		String emailMessage = sb.toString();
		System.out.println(" EMAIL MESSAGE ;"+ emailMessage+"hello");
		
		inputMap.put("to", "raju@gmail.com");
		inputMap.put("subject", "hey raju");
		inputMap.put("text", emailMessage);
	

		System.out.println("invoking mailgun integration");

		Map<String, String> response  = sendMail(inputMap);

		System.out.println(" response :"+response.toString());
		*/
		

	}

	@SuppressWarnings("deprecation")
	public static  Map<String, String> sendMail(Map<String, Object> inputMap){

		Map<String, String> response = new  HashMap<String, String>();
		try {

			if(inputMap == null){
				System.out.println(" inputMap is null ");
				return response;
			}
			String from = (String)inputMap.get("from");
			if(from == null){        
				//TODO: need to move from address to Property File/DB
				from = "notifications@meetexpert.in";
			}
			String to = (String)inputMap.get("to");
			if(to == null){
				System.out.println(" to is null ");
				response.put("error", "to is null");
				return response;
			}
			String subject = (String)inputMap.get("subject");
			if(subject == null){
				System.out.println(" subject is null ");
				response.put("error", "subject is null");
				return response;
			}
			String text = (String)inputMap.get("text");
			if(text == null){
				System.out.println(" text is null ");
				response.put("error", "text is null");
				return response;
			}


			StringBuilder sb = new StringBuilder();
			sb.append("from=");
			sb.append(URLEncoder.encode(from));
			sb.append("&to=");
			sb.append(URLEncoder.encode(to));
			sb.append("&subject=");
			sb.append(URLEncoder.encode(subject));
			sb.append("&html=");
			sb.append(URLEncoder.encode(text));

			String message = sb.toString();

			System.out.println("input");
			URL url = null;
			//TODO: need to move URL string to Property File/DB
			url = new URL("https://api.mailgun.net/v2/raju.mailgun.org/messages");
			HttpsURLConnection urlConn = null;   	        	
			urlConn = (HttpsURLConnection) url.openConnection();
			// Let the run-time system (RTS) know that we want input.
			urlConn.setDoInput (true);
			// Let the RTS know that we want to do output.
			urlConn.setDoOutput (true);
			//TODO: need to move content type to Property File/DB
			urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			// No caching, we want the real thing.
			urlConn.setUseCaches (false);
			urlConn.setRequestMethod("POST");
			//TODO: need to move api-key to Property File/DB
			String userpass = "api" + ":" + "key-88oyr75xbf8j9f534ebyd6b7vqoe4nq9";
			String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

			urlConn.setRequestProperty ("Authorization", basicAuth);
			urlConn.connect();
			DataOutputStream output = null;
			DataInputStream input = null;
			output = new DataOutputStream(urlConn.getOutputStream());
			output.writeBytes(message);
			output.flush();
			output.close();
			input = new DataInputStream (urlConn.getInputStream());
			String datastr = new String();
			String str = null;
			System.out.println(input);
			while (null != ((str = input.readLine()))) {
				datastr = datastr + str;   	        				
				System.out.println(str);
			}

			input.close ();

		}catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}






}
